package com.easylinkin.linkappapi.weather.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.tenant.entity.LinkappTenant;
import com.easylinkin.linkappapi.tenant.sevice.LinkappTenantService;
import com.easylinkin.linkappapi.weather.dto.WeatherResponseDTO;
import com.easylinkin.linkappapi.weather.entity.WeatherRecord;
import com.easylinkin.linkappapi.weather.mapper.WeatherRecordMapper;
import com.easylinkin.linkappapi.weather.service.WeatherService;
import com.fasterxml.jackson.databind.ObjectMapper;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 天气服务实现类
 */
@Service
@Slf4j
public class WeatherServiceImpl extends ServiceImpl<WeatherRecordMapper, WeatherRecord> implements WeatherService {

    @Autowired
    private WeatherRecordMapper weatherRecordMapper;

    @Autowired
    private LinkappTenantService tenantService;

    @Value("${weather.api.url:https://pm5vxm4vth.re.qweatherapi.com}")
    private String weatherApiUrl;

    @Value("${weather.api.key:}")
    private String weatherApiKey;

    @Override
    public void fetchAllTenantsWeatherData() {
        log.info("开始获取所有租户的天气数据");
        
        // 查询所有有经纬度信息的租户
        List<LinkappTenant> tenants = tenantService.list(
            new QueryWrapper<LinkappTenant>()
                .isNotNull("longitude")
                .isNotNull("longitude")
                .ne("longitude", "")
                .ne("longitude", "")
        );
        
        log.info("找到{}个有经纬度信息的租户", tenants.size());
        
        for (LinkappTenant tenant : tenants) {
            try {
                fetchAndSaveWeather(
                    Double.valueOf(tenant.getLongitude()),
                    Double.valueOf(tenant.getLatitude()),
                    tenant.getId()
                );
                
                // 避免频繁请求，休眠一秒
                Thread.sleep(1000);
            } catch (Exception e) {
                log.error("获取租户{}的天气数据失败: {}", tenant.getId(), e.getMessage(), e);
            }
        }
        
        log.info("完成所有租户天气数据获取");
    }

    @Override
    public List<WeatherRecord> getHistoryRecords(String tenantId, Date startTime, Date endTime) {
        return weatherRecordMapper.selectByTenantIdAndTimeRange(tenantId, startTime, endTime);
    }

    @Override
    public WeatherRecord getLatestRecord(String tenantId) {
        return weatherRecordMapper.selectLatestByTenantId(tenantId);
    }

    @Override
    public void fetchAndSaveWeather(Double longitude, Double latitude, String tenantId) {
        try {
            // 构建请求URL - 使用实时天气接口
            String url = String.format("%s/v7/weather/now?location=%.2f,%.2f", 
                weatherApiUrl, longitude, latitude);
            
            log.info("正在请求天气API: {}", url);
            
            // 发送HTTP请求
            HttpResponse<String> response = Unirest.get(url)
                .header("X-QW-Api-Key", weatherApiKey)
                .header("User-Agent", "LinkApp-WeatherService/1.0")
                .header("Content-Type", "application/json;charset=UTF-8")
                .header("Accept", "*/*")
                .header("Host", "pm5vxm4vth.re.qweatherapi.com")
                .header("Connection", "keep-alive")
                .asString();
            
            log.info("天气API响应状态: {}", response.getStatus());
            log.info("天气API响应内容: {}", response.getBody());
            
            if (response.getStatus() == 200) {
                // 解析响应JSON
                ObjectMapper objectMapper = new ObjectMapper();
                WeatherResponseDTO weatherResponse = objectMapper.readValue(response.getBody(), WeatherResponseDTO.class);
                
                if ("200".equals(weatherResponse.getCode()) && weatherResponse.getNow() != null) {
                    // 创建天气记录
                    WeatherRecord record = new WeatherRecord();
                    record.setTenantId(tenantId);
                    record.setCreateTime(new Date());
                    
                    // 设置实时天气数据
                    WeatherResponseDTO.NowWeather now = weatherResponse.getNow();
                    record.setObsTime(now.getObsTime());
                    record.setTemp(now.getTemp());
                    record.setFeelsLike(now.getFeelsLike());
                    record.setIcon(now.getIcon());
                    record.setText(now.getText());
                    record.setWind360(now.getWind360());
                    record.setWindDir(now.getWindDir());
                    record.setWindScale(now.getWindScale());
                    record.setWindSpeed(now.getWindSpeed());
                    record.setHumidity(now.getHumidity());
                    record.setPrecip(now.getPrecip());
                    record.setPressure(now.getPressure());
                    record.setVis(now.getVis());
                    record.setCloud(now.getCloud());
                    record.setDew(now.getDew());
                    
                    // 保存到数据库
                    weatherRecordMapper.insert(record);
                    log.info("天气数据保存成功，租户ID: {}", tenantId);
                } else {
                    log.error("天气API返回错误，状态码: {}", weatherResponse.getCode());
                }
            } else {
                log.error("天气API请求失败，HTTP状态码: {}", response.getStatus());
            }
        } catch (Exception e) {
            log.error("获取天气数据失败，租户ID: {}, 错误: {}", tenantId, e.getMessage(), e);
        }
    }
} 